<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
            <el-form-item label="企业" prop="enterpriseId">
                <!-- <el-cascader style="width: 300px;" v-model="value" :options="options"
                    @change="handleCascaderChange($event, 'query')"></el-cascader> -->

                <el-select v-model="queryParams.enterpriseId">
                    <el-option v-for="item in options" :key="item.value" :value="item.value" :label="item.label">
                    </el-option>
                </el-select>

            </el-form-item>
            <el-form-item label="时间" prop="nickName">
                <el-date-picker v-model="dates" type="daterange" range-separator="至" start-placeholder="开始日期"
                    @change="changeDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd" end-placeholder="结束日期">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="测评" prop="appraisalId">
                <el-select v-model="queryParams.appraisalId">
                    <el-option v-for="item in appraisalList" :key="item.id" :value="item.id"
                        :label="item.appraisalName">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">

            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
        <el-table v-loading="loading" :data="configurationList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="序号" align="center" width="55" type="index" />
            <el-table-column label="企业名称" align="center" prop="enterpriseName" min-width="200"
                :show-overflow-tooltip="true" />
            <el-table-column label="联系人" align="center" prop="contactPerson" min-width="100"
                :show-overflow-tooltip="true" />
            <el-table-column label="联系方式" align="center" prop="contactPhone" min-width="150"
                :show-overflow-tooltip="true" />
            <el-table-column label="测评名称" align="center" prop="appraisalName" min-width="200"
                :show-overflow-tooltip="true" />
            <el-table-column label="已测人数" align="center" prop="peopleNumber" min-width="100"
                :show-overflow-tooltip="true" />

            <el-table-column label="有效期开始时间" align="center" prop="validityBeginDate" min-width="120"
                :show-overflow-tooltip="true" />
            <el-table-column label="有效期结束时间" align="center" prop="validityFinishDate" min-width="120"
                :show-overflow-tooltip="true" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120" fixed="right">
                <template slot-scope="scope">
                    <!-- <el-button size="mini" type="text" @click="handleQr(scope.row)"
                        v-hasPermi="['enterpriseQR:enterpriseQR:qrCode']">企业二维码</el-button> -->
                    <el-button size="mini" type="text" @click="handleDetails(scope.row)"
                        v-hasPermi="['enterpriseQR:enterpriseQR:detail']">详情</el-button>
                    <el-button size="mini" type="text" @click="handleExport(scope.row)"
                        v-hasPermi="['enterpriseQR:enterpriseQR:export']">导出报告</el-button>

                   <el-button size="mini" v-if="scope.row.appraisalId == 8" type="text"
                        @click="handleExport1(scope.row)"
                        v-hasPermi="['enterpriseQR:enterpriseQRScl:edit']">导出企业整体报告</el-button>
                    <!-- <el-button size="mini" type="text" @click="handleUpdate(scope.row)"
                        v-hasPermi="['enterpriseQR:enterpriseQR:edit']">修改</el-button>
                    <el-button size="mini" type="text" @click="handleDelete(scope.row)"
                        v-hasPermi="['enterpriseQR:enterpriseQR:remove']">删除</el-button> -->
                </template>
            </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />
        <el-dialog title="评测结果分析" :visible.sync="openResult" width="700px" append-to-body>
            <scl90-vue ref="scl90Ref" :appraisalId="appraisalId" :detailId="detailId"
                v-if="appraisalId == 8"></scl90-vue>
            <anxiety-self-assessment ref="anxietyRef" :appraisalId="appraisalId" :detailId="detailId"
                v-if="appraisalId == 7"></anxiety-self-assessment>
            <burnout ref="burnoutRef" :appraisalId="appraisalId" :detailId="detailId" v-if="appraisalId == 1"></burnout>
            <careerInterest ref="careerRef" :appraisalId="appraisalId" :detailId="detailId" v-if="appraisalId == 5">
            </careerInterest>
            <childRelationshipAssessment ref="AssessmentRef" :appraisalId="appraisalId" :detailId="detailId"
                v-if="appraisalId == 10">
            </childRelationshipAssessment>
            <childRelationshipDiagnosis ref="DiagnosisRef" :appraisalId="appraisalId" :detailId="detailId"
                v-if="appraisalId == 4">
            </childRelationshipDiagnosis>
            <depressionSelfAssessment ref="depressionRef" :appraisalId="appraisalId" :detailId="detailId"
                v-if="appraisalId == 2">
            </depressionSelfAssessment>
            <maritalQuality ref="maritalRef" :appraisalId="appraisalId" :detailId="detailId" v-if="appraisalId == 9">
            </maritalQuality>
            <perceivedStress ref="stressRef" :appraisalId="appraisalId" :detailId="detailId" v-if="appraisalId == 6">
            </perceivedStress>
            <socialSupportRatingScale ref="socialSupportRef" :appraisalId="appraisalId" :detailId="detailId"
                v-if="appraisalId == 3"></socialSupportRatingScale>
        </el-dialog>
        <el-dialog title="历史测评" :visible.sync="openAppraisalList1" width="1200px" append-to-body>
            <el-table :data="AppraisalList1">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="序号" align="center" width="55" type="index" />
                <el-table-column label="测评名称" align="center" prop="appraisalName" min-width="150"
                    :show-overflow-tooltip="true" />
                <el-table-column label="用户名称" align="center" prop="nickName" min-width="100"
                    :show-overflow-tooltip="true" />
                <el-table-column label="得分" align="center" prop="appraisalScore" min-width="100"
                    :show-overflow-tooltip="true" />
                <el-table-column label="评测状态" align="center" prop="appraisalStatus" min-width="100"
                    :show-overflow-tooltip="true">
                    <template v-slot="scope">
                        <div v-if="scope.row.appraisalStatus == 0">进行中</div>
                        <div v-if="scope.row.appraisalStatus == 1">已完成</div>
                    </template>
                </el-table-column>
                <el-table-column label="开始时间" align="center" prop="appraisalBeginDate" min-width="160"
                    :show-overflow-tooltip="true" />
                <el-table-column label="结束时间" align="center" prop="appraisalFinishDate" min-width="160"
                    :show-overflow-tooltip="true" />
                <el-table-column label="性别" align="center" prop="userSex" min-width="100" :show-overflow-tooltip="true">
                    <template v-slot="scope">
                        <div v-if="scope.row.userSex == 0">男</div>
                        <div v-if="scope.row.userSex == 1">女</div>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right"
                    width="80">
                    <template slot-scope="scope">
                        <el-button size="mini" type="text" @click="handleViews(scope.row)">详情</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <pagination v-show="AppraisalList1Total > 0" :total="AppraisalList1Total"
                :page.sync="queryParamsAppraisalList1.pageNum" :limit.sync="queryParamsAppraisalList1.pageSize"
                @pagination="getuserAppraisalList1" />
        </el-dialog>


        <el-dialog title="企业二维码" :visible.sync="openqrCodeUrl" width="700px" append-to-body>
            <el-card class="box-card">
                <div slot="header" class="clearfix">
                    <el-button type="primary" size="mini" @click="downloadQRCode"
                        v-hasPermi="['enterpriseQR:enterpriseQR:downLoad']">下载</el-button>
                </div>
                <div ref="exportContainer" class="export-content">
                    <div>
                        <img :src="qrCodeUrl" class="content-image" />
                    </div>
                </div>
            </el-card>
        </el-dialog>
    </div>
</template>

<script>
import QRCode from 'qrcode'
import { userAppraisalList1 } from '@/api/member'
import { listQrCode, delQrCode } from '@/api/qrCode/qrCode.js'
import { enterpriseList } from "@/api/evaluation/appraisalTopic";
import { enterpriseUser, exportSDSWord1, exportSASWord1, exportSclWord1,exportSclWord2 } from '@/api/evaluationReport/index.js'


import VueHtml2pdf from 'vue-html2pdf'
import scl90Vue from '../cnps/scl90.vue'; //8
import anxietySelfAssessment from '../cnps/anxietySelfAssessment.vue'; //焦虑自我评估7
import burnout from '../cnps/burnout.vue'; //职业倦怠1
import careerInterest from '../cnps/careerInterest.vue'; //霍兰德职业兴趣5
import childRelationshipAssessment from '../cnps/childRelationshipAssessment.vue'; //亲子关系诊断10
import childRelationshipDiagnosis from '../cnps/childRelationshipDiagnosis.vue'; //亲子关系评估4
import depressionSelfAssessment from '../cnps/depressionSelfAssessment.vue'; //抑郁自我评估2
import maritalQuality from '../cnps/maritalQuality.vue'; //婚姻9
import perceivedStress from '../cnps/perceivedStress.vue'; //知觉压力6
import socialSupportRatingScale from '../cnps/socialSupportRatingScale.vue'; //社会支持评分量表3
export default {
    name: "enterpriseQRcompany",
    components: {
        VueHtml2pdf,
        scl90Vue,
        anxietySelfAssessment,
        burnout,
        careerInterest,
        childRelationshipAssessment,
        childRelationshipDiagnosis,
        depressionSelfAssessment,
        maritalQuality,
        perceivedStress,
        socialSupportRatingScale
    },
    data() {
        return {
            openqrCodeUrl: false,
            qrCodeUrl: '',
            appraisalId: '',
            detailId: '',
            openResult: false,
            appraisalListData: [],
            openAppraisalList1: false,
            // 查询参数
            queryParamsAppraisalList1: {
                pageNum: 1,
                pageSize: 10,
                userType: 2
            },
            AppraisalList1Total: 0,
            AppraisalList1: [],
            appraisalList: [],
            dates: [],
            options: [],
            copyenterpriseUserList: [],
            value: [],
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 配置维护表格数据
            configurationList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                nickName: undefined,
                appraisalId: undefined,
                enterpriseDeptId: undefined,
                enterpriseId: undefined,
                factoryId: undefined,
                enterpriseName: undefined, factoryName: undefined, enterpriseDeptName: undefined,
                pageNum: 1,
                pageSize: 10,
                params: {
                    endTime: undefined,
                    beginTime: undefined,
                }
            }
        };
    },
    created() {
        this.getList();
        enterpriseList().then(res => {
            this.appraisalList = res.rows
        })
        enterpriseUser().then(res => {
            let newRows = res.rows.filter(item => item.parentId == 0)
            newRows.forEach(element => {
                element.value = element.id
                element.label = element.enterpriseName
            });
            this.options = newRows
            // this.copyenterpriseUserList = res.rows
            // this.options = this.handleTree(res.rows)
            // 使用示例
            // const processedData = this.formatData(this.options);
            // console.log(processedData, 'this.handleTree(res.rows)')
        })
    },
    methods: {
       handleExport1(row) {
            const loading = this.$loading({
                lock: true,
                text: '正在导出中，请在导出列表中查看',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });

            exportSclWord2({
                qrId: row.id
            }).then(res => {
            })
            setTimeout(() => {
                loading.close();
            }, 3000);
        },
        downloadQRCode() {
            const link = document.createElement('a')
            link.href = this.qrCodeUrl
            link.download = '企业二维码.png'
            link.click()
        },
        handleQr(row) {
            let text = 'https://www.lqlxpt.com/pages/index/?userId=abc12'
            //    let  text = `https://blxlcp.cn/pages/index/?appraisalId=${row.appraisalId}`
            QRCode.toDataURL(text, {
                width: 200,
                margin: 2,
                color: {
                    dark: '#000000', // 二维码颜色
                    light: '#ffffff' // 背景色
                }
            }, (err, url) => {
                if (err) {
                    this.$message.error('生成二维码失败')
                    return
                }
                console.log(url)
                this.qrCodeUrl = url
                this.openqrCodeUrl = true
            })
        },
        handleViews(row) {
            this.appraisalId = row.appraisalId;
            this.detailId = row.id;
            this.openResult = true
        },
        getuserAppraisalList1() {
            userAppraisalList1(this.queryParamsAppraisalList1).then(response => {
                this.AppraisalList1 = response.rows;
                this.AppraisalList1Total = response.total;
            });
        },
        handleDetails(row) {
            this.$router.push({
                path: '/historyEvalution/index',
                query: {
                    id: row.id,
                    appraisalId: row.appraisalId,
                    enterpriseId: row.enterpriseId,
                }
            })
            // this.queryParamsAppraisalList1.appraisalId = row.appraisalId
            // this.queryParamsAppraisalList1.enterpriseDeptId = row.enterpriseDeptId
            // this.queryParamsAppraisalList1.enterpriseId = row.enterpriseId
            // this.queryParamsAppraisalList1.factoryId = row.factoryId
            // this.getuserAppraisalList1()
            //  this.openAppraisalList1 = true
        },
        handleExport(row) {
            const loading = this.$loading({
                lock: true,
                text: '正在导出中，请在导出列表中查看',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });

            let downLoadUrl = ''
            if (row.appraisalId == 2) {
                exportSDSWord1({
                    qrId: row.id
                }).then(res => {

                })
            }
            if (row.appraisalId == 7) {
                exportSASWord1({
                    qrId: row.id
                }).then(res => {

                })
            }
            if (row.appraisalId == 8) {
                exportSclWord1({
                    qrId: row.id
                }).then(res => {
                })
            }
            setTimeout(() => {
                loading.close();
            }, 3000);
            // this.download(downLoadUrl, {
            //     qrId: row.id
            // }, `export_${new Date().getTime()}.zip`)


        },
        changeDate(e) {
            this.queryParams.params.beginTime = e[0]
            this.queryParams.params.endTime = e[1]
        },
        handleCascaderChange(value, type) {
            const target = type === 'query' ? this.queryParams : this.form;

            // 更新ID字段
            target.enterpriseId = value[0] || '';
            target.factoryId = value[1] || '';
            target.enterpriseDeptId = value[2] || '';

            // 如果是表单类型，还需要更新名称
            if (type === 'form') {
                target.enterprisevalue = value;
                this.updateEnterpriseNames(value);
            }
        },

        /**
         * 更新企业相关名称
         * @param {Array} value 选中的值数组
         */
        updateEnterpriseNames(value) {
            const enterpriseMap = new Map(
                this.copyenterpriseUserList.map(item => [item.id, item.enterpriseName])
            );

            this.form.enterpriseName = enterpriseMap.get(value[0]) || '';
            this.form.factoryName = enterpriseMap.get(value[1]) || '';
            this.form.enterpriseDeptName = enterpriseMap.get(value[2]) || '';
        },
        formatData(data) {
            for (let i = 0; i < data.length; i++) {
                if (data[i].children && data[i].children.length === 0) {
                    data[i].children = undefined; // 关键步骤
                } else if (data[i].children) {
                    this.formatData(data[i].children); // 递归处理子级
                }
            }
            return data;
        },
        /** 查询配置维护列表 */
        getList() {
            this.loading = true;
            listQrCode(this.queryParams).then(response => {
                this.configurationList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dates = []
            this.value = []
            this.queryParams.enterpriseName = null
            this.queryParams.factoryName = null
            this.queryParams.enterpriseDeptName = null
            this.queryParams.enterpriseId = null
            this.queryParams.factoryId = null
            this.queryParams.enterpriseDeptId = null
            this.queryParams.params.beginTime = null
            this.queryParams.params.endTime = null
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        }
    }
};
</script>
<style scoped lang="scss">
.export-content {
    width: 600px;
    display: flex;
    justify-content: space-around;
}
</style>
